package cn.tedu._07vehicle.base.interceptors;

import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class RateLimitInterceptor implements HandlerInterceptor {
    private static final int MAX_COUNT = 2;
    private static final int WINDOW_SIZE = 60;
    //  {"192.168.1.11": 2, "192.168.1.12": 1, "192.168.1.13": 3}
    private final ConcurrentHashMap<String, Integer> clientCounts = new ConcurrentHashMap<>();
    //  {"192.168.1.11": "2025-11-18 14:22:00", "192.168.1.12": "2025-08-11 11:00:00",  "192.168.1.13": "2025-08-11 09:00:00"}
    private final ConcurrentHashMap<String, LocalDateTime> clientTimes = new ConcurrentHashMap<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.debug("进入网站限流的拦截器...");
      //1.获取客户端的IP地址;
        String clientIp=request.getRemoteAddr();
        //2.获取最后一次访问的时间;
        LocalDateTime lastTime = clientTimes.get(clientIp);
        /*
        1.情况一:第一次访问,lastTime == null,计数器清零;
        2.情况二:非第一次访问,lastTime != null;
          判断当前时间和最后一次访问时间间隔是否在1分钟内;
          1.情况1:不在1分钟内,计数器清零;
          2.情况2:在1分钟内,计数器增加1;
         */
        if (lastTime == null||LocalDateTime.now().isAfter(lastTime.plusSeconds(WINDOW_SIZE))) {
             clientCounts.put(clientIp,0);
             clientTimes.put(clientIp,LocalDateTime.now());
        }
        //3.1计数器+1
        Integer count = clientCounts.get(clientIp);
        count = count +1;
        clientCounts.put(clientIp,count);
        //4.判断计数器是否超过3;
        if (count > MAX_COUNT) {
            throw new RuntimeException("访问过于频繁,请稍后再试");
        }else  {
            return true;//放行
        }
  }
}
